from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager


def initialize_driver():
    """初始化并返回一个Chrome WebDriver实例，使用无头模式"""
    options = Options()
    options.headless = True  # 启用无头模式
    options.add_argument('--disable-gpu')  # 禁用GPU加速
    options.add_argument('--no-sandbox')  # 防止某些限制
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    return driver


def load_page(driver, url, wait_for_element=None, timeout=10):
    """加载网页并等待指定元素加载"""
    driver.get(url)
    if wait_for_element:
        # 等待直到指定的元素加载完毕
        WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located(wait_for_element)
        )
    return driver


def get_gold_price():
    """主逻辑函数"""
    url = "https://finance.sina.com.cn/nmetal/"
    driver = initialize_driver()

    try:
        # 加载网页并等待class为r_g_price_now的div元素出现
        load_page(driver, url, wait_for_element=(By.CLASS_NAME, "r_g_price_now"))

        # 定位到class为r_g_price_now的div控件
        price_element = driver.find_element(By.CLASS_NAME, "r_g_price_now")

        # 输出该控件的文本内容
        # print(f"当前价格: {price_element.text}")
        return price_element.text
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        # 关闭WebDriver
        driver.quit()

if __name__ == "__main__":
    get_gold_price()
